<?php

App::uses('AppModel', 'Model');

/**
 * ModuleSmsAccountMessage Model
 *
 * @property ModuleSmsAccount $ModuleSmsAccount
 * @property ModuleSmsBroadcastList $ModuleSmsBroadcastList
 */
class ModuleSmsAccountBroadcast extends AppModel {

    /**
     * Use database config
     *
     * @var string
     */
    public $useDbConfig = 'organisations';

    /**
     * Display field
     *
     * @var string
     */
    public $displayField = 'message';


    //The Associations below have been created with all possible keys, those that are not needed can be removed

    /**
     * belongsTo associations
     *
     * @var array
     */
    public $belongsTo = array(
        'ModuleSmsAccount' => array(
            'className' => 'ModuleSmsAccount',
            'foreignKey' => 'module_sms_account_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'ModuleSmsBroadcastList' => array(
            'className' => 'ModuleSmsBroadcastList',
            'foreignKey' => 'module_sms_broadcast_list_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'OrganisationMemberCategory' => array(
            'className' => 'OrganisationMemberCategory',
            'foreignKey' => 'organisation_member_category_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

    public function getHistory($organisation_id, $offset = 0, $limit = 10) {
        
        $list = $this->find('all', array(
            'contain' => array(
                'ModuleSmsAccount', 'ModuleSmsBroadcastList', 'OrganisationMemberCategory'
            ),
            'conditions' => array(
                'ModuleSmsAccount.organisation_id' => $organisation_id
            ),
            'offset' => $offset,
            'limit' => $limit,
            'order' => array('ModuleSmsAccountBroadcast.id' => 'desc')
        ));
        
        $results = array();
        
        foreach($list as $l) {
            if( isset($l['ModuleSmsBroadcastList']['id']) ) {
                $response = $this->ModuleSmsBroadcastList->getListSize($l['ModuleSmsAccount']['id'], $l['ModuleSmsBroadcastList']['id']);
                
                array_push($results, array(
                    'broadcast_id' => $l['ModuleSmsAccountBroadcast']['id'],
                    'list_id' => $l['ModuleSmsBroadcastList']['id'],
                    'list_name' => $l['ModuleSmsBroadcastList']['name'],
                    'message' => $l['ModuleSmsAccountBroadcast']['message'],
                    'schedule' => $l['ModuleSmsAccountBroadcast']['send_at'],
                    'sent' => $l['ModuleSmsAccountBroadcast']['sent'],
                    'type' => 'custom',
                    'size' => $response['size']
                ));
            }
            
            if( isset($l['OrganisationMemberCategory']['id']) ) {
                array_push($results, array(
                    'broadcast_id' => $l['ModuleSmsAccountBroadcast']['id'],
                    'list_id' => $l['OrganisationMemberCategory']['id'],
                    'list_name' => "All " . $l['OrganisationMemberCategory']['name'],
                    'message' => $l['ModuleSmsAccountBroadcast']['message'],
                    'schedule' => $l['ModuleSmsAccountBroadcast']['send_at'],
                    'sent' => $l['ModuleSmsAccountBroadcast']['sent'],
                    'type' => 'predefined',
                    'size' => ClassRegistry::init('OrganisationMember')->getTotalMembersByCategory($organisation_id, $l['OrganisationMemberCategory']['id'])
                ));
            }
            
            if( $l['ModuleSmsAccountBroadcast']['organisation_member_category_id'] == -1 ) {
                array_push($results, array(
                    'broadcast_id' => $l['ModuleSmsAccountBroadcast']['id'],
                    'list_id' => -1,
                    'list_name' => 'Everyone',
                    'message' => $l['ModuleSmsAccountBroadcast']['message'],
                    'schedule' => $l['ModuleSmsAccountBroadcast']['send_at'],
                    'sent' => $l['ModuleSmsAccountBroadcast']['sent'],
                    'type' => 'predefined',
                    'size' => ClassRegistry::init('OrganisationMember')->getTotalMembers($organisation_id)
                ));
            }
        }
        
        if( $results ) {
            return array('status' => 'success', 'history' => $results);
        }
        
        return array('status' => 'failed', 'messsage' => 'No previous broadcast records found.');
    }
    
    public function setProcessed($broadcast_id, $processed = 1) {
        $this->updateAll(array(
            'ModuleSmsAccountBroadcast.sent' => $processed
        ), array(
            'ModuleSmsAccountBroadcast.id' => $broadcast_id
        ));
    }
    
    public function updateSendCounters($broadcast_id, $sent_offset, $sent_count) {
        $this->id = $broadcast_id;
        
        $this->updateAll(array(
            'ModuleSmsAccountBroadcast.sent_offset' => intval($this->field('sent_offset')) + intval($sent_offset),
            'ModuleSmsAccountBroadcast.sent_count' => intval($this->field('sent_count')) + intval($sent_count)
        ), array(
            'ModuleSmsAccountBroadcast.id' => $broadcast_id
        ));
    }
}
